<?php

namespace app\admin\controller\check;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\model\crud\StoreOrderService;
use think\Db;
use think\Loader;

/**
 * 清洁审核管理
 *
 * @icon fa fa-user
 */
class FreeClean extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    protected $noNeedRight = ['getSaleMan'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('check.FreeClean');
        $this->view->assign('getRejuctTypeList', $this->model->getRejuctTypeList());
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch = true;
        $this->searchFields = 'proprietor_name,phone,address,elevator_no';
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $where = [];
            $filter = $this->request->get('filter');
            $offset = $this->request->get('offset');
            $order = $this->request->get('order');
            $sort = $this->request->get('sort');
            $limit = $this->request->get('limit');
            $filter = json_decode($filter, true);
            $string = '';
            foreach ($filter as $w => $v) {
                if ($w == 'submit_check_time') {
                    $time_arr = explode(' - ', $v);
                    $where['submit_check_time'] = ['between', [strtotime($time_arr[0]), strtotime($time_arr[1])]];
                    //  $where_new['end_time'] = ['<=',$time_arr[1]];
                } else if ($w == 'uid' || $w == 'salesman_id' || $w == 'status' || $w == 'free_clean.id' || $w == 'audit_status' || $w == 'clean_area') {
                    $where['free_clean.' . $w] = $v;
                } else if ($w == 'proprietor_name' || $w == 'phone' || $w == 'plot_name' || $w == 'elevator_no') {
                    $where['free_clean.' . $w] = ['like', '%' . $v . '%'];
                } else if ($w == 'province' || $w == 'city' || $w == 'area') {
                    $string .= $v . '-';
                } else if ($w == 'accuracy') {
                    if ($v == 0) {
                        $where['lon'] = '';
                    } else {
                        $where['lon'] = ['<>', ''];
                    }
                }
            }
            if (!isset($where['free_clean.status'])) {
                $where['free_clean.status'] = ['>', 1];
            }
            if ($string) {
                $string = substr($string, 0, -1);
                $where['address'] = $string;
            }
            $count = $this->model
                ->with(['saleman'])
                ->where($where)
                //  ->where($new_where)
                ->count();
            $list = $this->model
                ->with(['saleman'])
                ->where($where)
                //->where($new_where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $w => &$v) {
                $v->getRelation('saleman')->visible(['real_name']);
                $v['accuracy'] = 0;
                $v['type_text'] = '加装电梯';
                if ($v['lon']) {
                    $v['accuracy'] = 1;
                }
            }
            $sql = $this->model->getLastSql();
            $result = array("total" => $count, "rows" => $list, 'sql' => $sql);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['create_time'] = time();
            $params['admin_id'] = $this->auth->id;
            $image_arr = explode('aliyuncs.com', $params['logo']);
            if ($params['logo']) {
                $params['logo'] = $image_arr[1];
            }
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
            $randStr = str_shuffle($str);
            $rands = substr($randStr, 0, 6);
            $params['code'] = $rands;
            $res = $this->model->insert($params);
            if ($res) {
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['up_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //获取详情信息
        $this->model->getDetailArr($row);
        $address = explode('-', $row['address']);
        $row['province'] = $address[0];
        $row['city'] = $address[1];
        $row['region'] = $address[2];
        $this->view->assign("row", $row);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where(['id' => $row['id']])->delete();
        $this->success();
    }

    /**
     * 详情
     */
    public function detail($ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['up_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //获取详情信息
        $this->model->getDetailArr($row);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 审核
     */
    public function audit($ids = '')
    {
        if (!$ids) {
            $ids = $this->request->request('id');
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['up_time'] = time();
                    if ($params['audit_status'] == 1) {
                        $params['remark'] = '';
                        $params['remark_type'] = 0;
                        $params['is_can_update'] = 0;
                        $this->setFreeServiceOrder($row['id'], $row['uid'], $row);
                    } else {
                        if ($params['remark_type'] == 0) {
                            $this->error('未选择驳回理由');
                        }
                        if ($params['remark_type'] == 1) {
                            $params['remark'] = '电梯使用标识不清晰';
                        } else if ($params['remark_type'] == 2) {
                            $params['remark'] = '联系电话联系不上';
                        } else if ($params['remark_type'] == 3) {
                            $params['remark'] = '电梯非加装电梯';
                        } else if ($params['remark_type'] == 4) {
                            $params['remark'] = '地址填写错误';
                        } else if ($params['remark_type'] == 5) {
                            $params['remark'] = '地址不在三环内';
                        }
                    }
                    var_dump($params);
                    $row['status'] = 3;
                    $row['check_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //获取详情信息
        $this->model->getDetailArr($row);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 审核
     */
    public function again_audit($ids = '')
    {
        if (!$ids) {
            $ids = $this->request->request('id');
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['up_time'] = time();
                    if ($params['audit_status'] == 1) {
                        $params['remark'] = '';
                        $params['remark_type'] = 0;
                        $params['is_can_update'] = 0;
                        $this->setFreeServiceOrder($row['id'], $row['uid'], $row);
                    } else {
                        if ($params['remark_type'] == 0) {
                            $this->error('未选择驳回时间');
                        }
                        if ($params['remark_type'] == 1) {
                            $params['remark'] = '电梯使用标识不清晰';
                        } else if ($params['remark_type'] == 2) {
                            $params['remark'] = '联系电话联系不上';
                        } else if ($params['remark_type'] == 3) {
                            $params['remark'] = '电梯非加装电梯';
                        } else if ($params['remark_type'] == 4) {
                            $params['remark'] = '地址填写错误';
                        } else if ($params['remark_type'] == 5) {
                            $params['remark'] = '地址不在三环内';
                        }
                    }
                    $row['status'] = 3;
                    $row['check_time'] = time();

                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //获取详情信息
        $this->model->getDetailArr($row);
        $this->view->assign("row", $row);
        $this->assignconfig("row", $row);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function do_assign($ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['up_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //获取详情信息
        $this->model->getDetailArr($row);
        $this->view->assign("row", $row);
        if ($row['salesman_id'] > 0) {
            $row['is_have_saleman'] = 1;
        } else {
            $row['is_have_saleman'] = 0;
        }
        $this->assignconfig("is_have_saleman", $row['is_have_saleman']);
        return $this->view->fetch();
    }

    /**
     * 获取业务列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSaleMan()
    {
        $keValue = $this->request->request("keyValue");
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $show_province_id = [];
            $new_where = [
                //'class_status'=>0
            ];
            if ($keValue) {
                $keValue = explode(',', $keValue);
                // $new_arr = array_merge($keValue,$show_province_id);
                $new_where = [
                    'id' => ['in', $keValue]
                ];
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = Db::name('user')
                ->where($where)
                ->where(['is_promoter' => 1])
                ->where($new_where)
                ->count();

            $list = Db::name('user')
                ->where($where)
                ->where(['is_promoter' => 1])
                ->where($new_where)
                ->order('uid desc')
                ->select();
            $sql = Db::name('user')->getLastSql();
            $list = collection($list)->toArray();
            $new_list = [];
            foreach ($list as $w => $v) {
                $new_data = [
                    'id' => $v['uid'],
//                    'province_id' => $v['province_id'],
                    'title' => $v['real_name'],
                ];
                $new_list[$w] = $new_data;
            }
            $result = array("total" => $total, "list" => $new_list, "sql" => $sql);
            return json($result);
        }
    }


    /**
     * 详情
     */
    public function do_most_assign($ids = '')
    {
//        $row = $this->model->get($ids);
//        if (!$row) {
//            $this->error(__('No Results were found'));
//        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $check_id = $this->request->get("check_id");
            if ($params) {
                try {
                    $check_id_arr = explode(',', $check_id);
                    if (count($check_id) == 0) {
                        $this->error('尚未选择任何一笔订单');
                    }
                    $params['up_time'] = time();
                    // $params['salesman_id'] = time();
                    $result = $this->model->where(['id' => ['in', $check_id_arr], 'salesman_id' => 0])->update($params);
                    if ($result !== false) {
                        $this->success();
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 更新经纬度
     */
    public function update_location($ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['up_time'] = time();
                    // $params['salesman_id'] = time();
                    $result = $this->model->where(['id' => $row['id']])->update($params);
                    if ($result !== false) {
                        $this->success();
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed $searchfields 快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    public function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if ($v[0] == 'free_clean.accuracy') {
                    $v[0] = 'free_clean.lon';
                    if ($v[2] == 0) {
                        $v[1] = '=';
                        $v[2] = '';
                    } else {
                        $v[1] = '<>';

                        $v[2] = '';
                    }
                }
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }


//    /**
//     *
//     * @return \think\response\Json
//     * @throws \think\db\exception\DataNotFoundException
//     * @throws \think\db\exception\ModelNotFoundException
//     * @throws \think\exception\DbException
//     */
//    public function getSaleMan()
//    {
//        $keValue = $this->request->request("keyValue");
//        $this->request->filter(['strip_tags']);
//        if ($this->request->isAjax()) {
//            $show_province_id = [];
//            $new_where = [];
//            if ($keValue) {
//                $keValue = explode(',', $keValue);
//                // $new_arr = array_merge($keValue,$show_province_id);
//                $new_where = [
//                    'id' => ['in', $keValue]
//                ];
//            }
//
//            $page = $this->request->request("pageNumber");
//            //分页大小
//            $pagesize = $this->request->request("pageSize");
//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//
//            $total = Db::name('grade')
//                ->where($where)
//                ->where(['system_id'=>$this->auth->system_id])
//                ->where($new_where)
//                ->count();
//
//            $list =Db::name('grade')
//                ->where($where)
//                ->where(['system_id'=>$this->auth->system_id])
//                ->where($new_where)
//                ->page($page, $pagesize)
//                ->order('id desc')
//                ->select();
//            $sql = Db::name('grade')->getLastSql();
//            $list = collection($list)->toArray();
//            $new_list = [];
//            foreach ($list as $w => $v) {
//                $new_data = [
//                    'id' => $v['id'],
////                    'province_id' => $v['province_id'],
//                    'title' => $v['grade_name'],
//                ];
//                $new_list[$w] = $new_data;
//            }
//            $result = array("total" => $total, "list" => $new_list,"sql"=>$sql);
//            return json($result);
//        }
//    }

    public function setFreeServiceOrder($free_clean_id, $uid, $data = [])
    {
        $result_info = get_method('https://shopapi.tixiwe.com/api/v2/public/set_order?letter=Fw');
        $result_info = json_decode($result_info, true);
        $arr['service_id'] = $result_info['data']['number'];
        // $arr['service_id']=date('YmdHis').rand(100000,999999);
        $arr['order_id'] = 'free_clean_' . $free_clean_id;
        $info = Db::name('store_order_service')->where(['order_id' => $arr['order_id']])->find();
        if ($info) {
            return true;
        }
        if ($data['elevator_type'] == 1) {
            $elevator_type = '630公斤以下';
        } else if ($data['elevator_type'] == 2) {
            $elevator_type = '800公斤';
        } else {
            $elevator_type = '1000公斤';
        }
        $arr['lift_id'] = '';
        $arr['sku'] = '';
        $arr['first_service'] = '';
        $arr['end_service'] = '';
        $arr['moth_first_service'] = '';
        $arr['moth_end_service'] = '';
        $arr['moth'] = date('m');
        $arr['year'] = date('Y');
        $arr['add_time'] = time();
        $arr['service_time'] = time();
        $arr['package'] = '免费清洁';
        $arr['specifications'] = $elevator_type;
        $arr['duration'] = '单次';
        $arr['type'] = 1;
        $arr['free_clean_id'] = $free_clean_id;
        $arr['uid'] = $uid;
        $res = Db::name('store_order_service')->insert($arr);
        return $res;
    }

}
